package com.JavaNet.chapter7_urlConnection.jsonPoster;


import com.alibaba.fastjson.JSONObject;
import com.JavaNet.chapter7_urlConnection.entity.User;

import java.io.*;

import java.net.HttpURLConnection;

import java.net.URL;
import java.nio.charset.StandardCharsets;

/**
 * @author : wushikai
 * <p>
 * date : 2021-04-20
 */

public class JsonPoster {



    private final static String URL = "http://localhost:8888/api/loginj";

    private static HttpURLConnection getConnection(String urlStr) throws IOException {

        URL url = new URL(urlStr);

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        connection.setDoOutput(true);

        connection.setDoInput(true);

        connection.setRequestMethod("POST");

        connection.setUseCaches(false);

        connection.setInstanceFollowRedirects(true);

        connection.setRequestProperty("Accept", "application/json");  //接收的数据也是json

        connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");  //传输的数据是json

        connection.connect();

        return connection;


    }

    public static void main(String[] args) throws IOException, ClassNotFoundException {


        //连接服务器

        HttpURLConnection connection = getConnection(URL);

        DataOutputStream out = new DataOutputStream(connection.getOutputStream());

        JSONObject obj = new JSONObject();

        obj.put("id", User.create().getId());
        obj.put("username", User.create().getUsername());
        obj.put("password", User.create().getPassword());

        System.out.println("要传送的参数 ==> " + obj.toString());

        //  传入编码为UTF-8格式的json数据

        out.write(obj.toString().getBytes(StandardCharsets.UTF_8));

        out.flush();

        out.close();

        //获得服务器返回的结果


        InputStream inputStream = connection.getInputStream();

        //  DataInputStream dataInputStream = new DataInputStream(   inputStream );

        // 远端序列化报错  invalid stream header: 7B22E6B6  底层原理不明白, 不懂错在那里;  mark
        // ObjectInputStream inputStream = new ObjectInputStream( in);

        // JSONObject jsonObject = (com.alibaba.fastjson.JSONObject)inputStream.readObject();

        // System.out.println(jsonObject.toString() );


 /*
        这种方式读取数据有误? 不知道为什么 mark
        byte[] bytes = new byte[30];
        int index = bytes.length;

      while (index > 0) {

            index = inputStream.read(bytes, 0, index);

            System.out.print(new String(bytes, StandardCharsets.UTF_8));

        }
*/



        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

        String line ;
        while ((line = bufferedReader.readLine()) != null) {
            System.out.println(line);
        }


        inputStream.close();
        bufferedReader.close();

    }


}
